package org.ash.socket.bio;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket 多线程版版本
 * 缺点
 * 1. 线程无限增加
 * 2. 假设连接上来不发送数据，会一直阻塞在read（）方法，导致线程会越来越多
 * 3. 线程切换
 *
 * @author Ashin
 */
public class ServerSocketMultiThreadDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);

        while (true) {
            System.out.println("等待连接");
            Socket socket = serverSocket.accept();
            System.out.println("连接成功..." + socket);

            new Thread(() -> {
                try {
                    handleSocket(socket);


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }


    }

    public static void handleSocket(Socket socket) throws IOException {
        byte[] bytes = new byte[1025];
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        int len = bis.read(bytes);

        if (len != -1) {
            System.out.println("接收到客户端数据:" + new String(bytes, 0, len));
        }

        socket.getOutputStream().write("I receive".getBytes());
        socket.getOutputStream().flush();

        socket.close();
        System.out.println("连接关闭..." + socket);
    }
}
